package com.ebelter.nb.ui.activitys;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import com.ebelter.btcomlib.models.bluetooth.products.nb.BondDevices;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.utils.MD5Utils;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.VerifyUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.nb.R;
import com.ebelter.nb.constants.NbConstants;
import com.ebelter.nb.model.dao.DbUtils;
import com.ebelter.nb.model.http.HttpResponse2;
import com.ebelter.nb.model.http.MyStringCallback2;
import com.ebelter.nb.model.http.request.NbNetUtils;
import com.ebelter.nb.model.http.response.BandDeviceListResponse;
import com.ebelter.nb.model.http.response.Login_R;
import com.ebelter.nb.utils.NbUtitls;

public class LoginActivity extends NBBaseActivity {

    public static final String TAG = "LoginActivity";

    EditText cb1_ed;
    EditText cb2_ed;

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        super.initView();
        cb1_ed = findViewById(R.id.cb1_ed);
        cb2_ed = findViewById(R.id.cb2_ed);
        cb1_ed.setText(NbUtitls.getLoginUserId());
    }


    @Override
    protected void initData() {
        String userId=NbUtitls.getLoginUserId();
        String authkey=NbUtitls.getLoginAuthkey();
        String phone = UserSpUtil.readString(NbConstants.User.phone);
        String psw = UserSpUtil.readString(NbConstants.User.wsp);
        if (NetUtils.available()
                &&!TextUtils.isEmpty(authkey)
                &&!TextUtils.isEmpty(userId)
                &&!TextUtils.isEmpty(phone)
                &&!TextUtils.isEmpty(psw)){
            //说明已经登录过了
            Bundle bundle = new Bundle();
            bundle.putBoolean(MainActivity.GetBandListFromNet,true);//这个是为了进入主界面 重新拉取用户信息 确保最新的数据
            bundle.putBoolean(MainActivity.GetUserInfoFromNet,true);
            startActivity(MainActivity.class,bundle);
        }
        cb1_ed.setText(phone);


    }

    //登录按钮
    public void login(View view) {
        if (!NetUtils.available()) {
            ToastUtil.show(R.string.Network_error);
            return;
        }
        DbUtils.deleteTable(BondDevices.class);//先删除掉

        final String phone = cb1_ed.getText().toString().trim();
        String psw = cb2_ed.getText().toString().trim();

        if (TextUtils.isEmpty(phone)) {
            ToastUtil.show("手机号码不能为空");
            return;
        }

        if (!VerifyUtils.isMobile(phone)) {
            ToastUtil.show("手机号码格式不正确");
            return;
        }

        if (TextUtils.isEmpty(psw)) {
            ToastUtil.show("密码不能为空");
            return;
        }

        UserSpUtil.removeAll();

        final String pswMd5 = MD5Utils.getMd5(psw);
//{"authKey":"","data":{"loginName":"13826672468","pwd":"e10adc3949ba59abbe56e057f20f883e"},"bizId":"01","funcId":"05","version":"05"}
        NbNetUtils.getInstance().login(this, phone,pswMd5 , new HttpResponse2<Login_R>() {
            @Override
            public void result(boolean isRequestSuccess, String requestResultDesc, int requestResultCode, Login_R login_r, String s) {

                LogUtils.i(TAG, s);
                if (isRequestSuccess) {

//                    if (login_r != null && login_r.resultMessage != null){
//                        if (requestResultCode == MyStringCallback2.SUCCESS) {
//                            //登录成功
//                            UserSpUtil.writeString(NbConstants.User.phone, phone);
//                            UserSpUtil.writeString(NbConstants.User.wsp, pswMd5);
//                            saveUserData(login_r);
//                            getBandDeviceFromNet(login_r.resultMessage.phone);
//                        }else {
//                            ToastUtil.show("登录失败");
//                        }
//
//                    }else {
//                        ToastUtil.show("登录失败");
//                    }
                    if (requestResultCode == MyStringCallback2.SUCCESS) {
                        //登录成功
                        UserSpUtil.writeString(NbConstants.User.phone, phone);
                        UserSpUtil.writeString(NbConstants.User.wsp, pswMd5);
                        saveUserData(login_r);
                        getBandDeviceFromNet(login_r.resultMessage.phone);

                    } else if (requestResultCode == 0 || requestResultCode == 2) {
                        //登录失败
                        ToastUtil.show("账号或者密码错误");
                    } else if (requestResultCode == 3) {
                        //当前手机号未注册
                        ToastUtil.show("当前手机号未注册");
                    } else {
                        ToastUtil.show("登录失败");
                    }


                } else {
                    ToastUtil.show("登录失败");
                }


            }
        });


    }

    private void getBandDeviceFromNet(final String user_id) {



        NbNetUtils.getInstance().getUserBandList(this, user_id, new HttpResponse<BandDeviceListResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, BandDeviceListResponse bandDeviceListResponse, String s) {
                LogUtils.i(TAG, "----getUserBandList--" + s);
                LogUtils.i("getUserBandList",TAG+"----getUserBandList--"+s);
                if (isRequestSuccess && bandDeviceListResponse != null && bandDeviceListResponse.status == 0) {

                    if (bandDeviceListResponse.data != null) {
                        DbUtils.deleteTable(BondDevices.class);//先删除掉
                        for (int i = 0; i < bandDeviceListResponse.data.size(); i++) {
                            BandDeviceListResponse.DataBean dataBean = bandDeviceListResponse.data.get(i);
                            BondDevices bondDevices = new BondDevices();
                            bondDevices.user_id = user_id;
                            bondDevices.type = dataBean.type;
                            bondDevices._id = dataBean.id;//序列号
                            bondDevices.sn_number = dataBean.sn_number;
                            bondDevices.device_id = dataBean.device_id;//设备的IMEI码
                            bondDevices.create_time = dataBean.create_time;//创建的时间
                            bondDevices.save();

                        }
                    }
                    Bundle bundle=new Bundle();
                    bundle.putBoolean(MainActivity.GetBandListFromNet,false);
                    bundle.putBoolean(MainActivity.GetUserInfoFromNet,false);
                    startActivity(MainActivity.class,bundle);
                    finish();


                } else {
                    ToastUtil.show("登录失败");
                }


            }
        });

    }





    //保存用户数据
    private void saveUserData(Login_R login_r) {
        //这里不需要判断了对象是否为空了 前面已经判断过了
        UserSpUtil.writeString(NbConstants.User.authkey, login_r.resultMessage.authkey);
        UserSpUtil.writeString(NbConstants.User.phone, login_r.resultMessage.phone);
        UserSpUtil.writeString(NbConstants.User.birthday, TimeUtils.jianrongBirthdayStr(login_r.resultMessage.birthday));//yyyy-MM-dd
        UserSpUtil.writeString(NbConstants.User.email, login_r.resultMessage.email);
        UserSpUtil.writeString(NbConstants.User.name, login_r.resultMessage.name);
        UserSpUtil.writeInt(NbConstants.User.height, NumUtils.string2Int(login_r.resultMessage.height));
        UserSpUtil.writeFloat(NbConstants.User.weight, NumUtils.string2Float(login_r.resultMessage.weight));
        UserSpUtil.writeInt(NbConstants.User.sex, NumUtils.string2Int(login_r.resultMessage.sex));
        UserSpUtil.writeInt(NbConstants.User.profession, login_r.resultMessage.profession);//0普通1运动员
        UserSpUtil.writeString(NbConstants.User.modifydate, login_r.resultMessage.modifydate);
    }

    public void registerBt(View view) {
        Intent intent = new Intent(this, PhoneRegisterActivity.class);
        startActivity(intent);
//        Intent addDeviceIntent = new Intent(this,AddDeviceActivity.class);
//        startActivity(addDeviceIntent);
    }

    public void tv_forgot_password(View view) {
        Intent intent = new Intent(this, FindPswActivity1.class);
        startActivity(intent);
    }


}
